package com.itheima.aop;

import com.alibaba.fastjson.JSONObject;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;
    //@Around注解的方法参数不能随意修改,可以通过注解注入对象
    @Around("@annotation(com.itheima.anno.Log)")
    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.jwtParse(jwt);


        //操作人id
        Integer operateUser = (Integer) claims.get("id");
        //操作时间
        LocalDateTime operateTime=LocalDateTime.now();
        //操作类名
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        //操作方法名
        String methodName = proceedingJoinPoint.getSignature().getName();
        //操作参数
        Object[] args = proceedingJoinPoint.getArgs();
        String methodParams = Arrays.toString(args);
        //原始方法执行
        long begin = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        long end = System.currentTimeMillis();
        //返回值
        String returnValue = JSONObject.toJSONString(result);
        //操作耗时
        long costTime = end - begin;

        OperateLog operateLog=new OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnValue,costTime);
        operateLogMapper.insert(operateLog);
        log.info("操作日志:{}",operateLog);
        return result;
    }
}
